package com.jt.filter;

import org.apache.http.HttpHeaders;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * 基于此全局过滤器对请求url进行黑白名单识别
 * @ConfigurationProperties 注解描述类时,用于告诉系统底层
 * 要从配置文件中读取指定配置信息(prefix属性用于指定读取哪部分
 * 前缀对应的信息)
 */
//@ConfigurationProperties(prefix = "web.request")
//@Component
public class BlackUrlGlobalFilter implements GlobalFilter, Ordered {//Authentication(认证)

    private List<String> blackUrls=new ArrayList<>();
    /**
     * 当系统底层读取@ConfigurationProperties(prefix = "web.request")
     * 注解中描述的内容时,会自动基于名字调用此set方法
     */
    public void setBlackUrls(List<String> blacks) {
        this.blackUrls = blacks;
    }

    /**
     * 此方法为一个处理请求的方法
     * @param exchange 基于此对象获取请求和响应
     * @param chain 过滤链对象
     * @return SpringWebFlux中的Mono对象(一个Publisher对象),
     * 是springframework5.0后推出的新特性,
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange,
                             GatewayFilterChain chain) {
        //1.获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.获取请求url
        String urlPath=request.getURI().getPath();//nacos/provider/echo/gateway
        System.out.println("blackPath="+blackUrls);
        System.out.println("urlPath="+urlPath);
        //3.对请求url进行黑白名单分析
        //黑名单则请求到此结束
        if(blackUrls.contains(urlPath)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//401
            response.getHeaders()
                    .add(HttpHeaders.CONTENT_TYPE,"text/html;charset=utf-8");
            DataBuffer dataBuffer=
                    response.bufferFactory()
                            .wrap("请求url是黑名单".getBytes());
            return response.writeWith(Mono.just(dataBuffer));
        }
        //白名单则放行(执行下一步,假如有下个过滤器,就执行下一个过滤器)
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        return -1;
    }
}